<?php
/**
 * @Author: Ron Chen
 * @Date:   2016-12-05 21:56:11
 * @Last Modified by:   Ron Chen
 * @Last Modified time: 2017-03-11 21:38:01
 */

namespace common\services;

use Yii;
/**
*  参数获取服务
*/
class MysqlService
{

	/**
	 * 输出查询的 SQL 
	 * @params $query eg: User::find() ->select(['username'])->where(['id'=>[1,2,3,4])
	 */
	public static function getSql($query){
		return $query->createCommand()->getRawSql();
	}

	/**
	 * 批量查询操作
	 * eg: 
		foreach(Member::find()->batch(1000) as $value){
		    //do something
		    //print_r(count($value));
		}
	 */
	public static function batch($model,$num=100){
		return $model::find()->batch($num);
	}

	/**
	 * 判断某个 ID 是否存在
	 */
	public static function validateAttribute($model, $attribute){
		$value = $model->$attribute;
	    if (!$model::find()->where([$attribute => $value])->exists()) {
	       $model->addError($attribute, 'NOT exists');
	    }
	}

	/**
	 * 数据库事务操作
	 * eg: Yii::$app->db->transaction(function() {
			    $order = new Order($customer);
			    $order->save();
			});
	 * -----------------------------
	 * $transaction = Yii::$app->db->beginTransaction();
		try {
		    $order = new Order($customer);
		    $order->save();
		    $transaction->commit();
		} catch (\Exception $e) {
		    $transaction->rollBack();
		    throw $e;
		}
	 */
	public static function beginTransaction($function){
		return Yii::$app->db->transaction($function);
	}
}